package com.itcrx.datastructure;

import java.util.Iterator;
import java.util.function.Consumer;

/**
 * @author NoobMaster69  * @date 2024/5/30 0030 星期四 16:24
 */

/*
    动态数组
 */
public class DynamicArray implements Iterable<Integer>{
    private int size = 0;   //逻辑大小
    private int capacity = 8;   //容量
    private int[] array = {};
    //像最后位置增加元素
    public void addLast(int element){
        add(size,element);
    }


    //索引位置增加
    public void add(int index,int element){
        checkAndGrow();

        if (index >= 0 && index < size) {
            System.arraycopy(array,index,array,index + 1,size - index);
        }
        array[index] = element;
        size++;
    }

    private void checkAndGrow() {
        if(size == 0){
            array = new int[]{8};
        }else if(size == capacity){
            //扩容检查
            capacity += capacity >> 1;
            int[] newArr = new int[capacity];
            System.arraycopy(array,0,newArr,0,size);
            array = newArr;
        }
    }

    //得到某个
    public int get(int index) {
        return array[index];
    }
    //遍历方法一
    public void forEachMy(Consumer<Integer> consumer) {
        for (int i = 0;i < size; i++) {
            consumer.accept(array[i]);
        }
    }
    //遍历方法二
    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            int i = 0;
            @Override
            public boolean hasNext() {
                return i <size;
            }

            @Override
            public Integer next() {
                return array[i++];
            }
        };
    }

    //删除
    public int remove(int index){
        int remove = array[index];
        if(index < size -1){
            System.arraycopy(array,index + 1,array,index,size - index - 1);

        }
        size--;
        return remove;
    }



}
